
#include "my_app.h"
#include "PCF85063.h" //时钟驱动
#include <sys/time.h>
#include "esp_log.h"
#include "esp_netif_sntp.h"
#include "lwip/ip_addr.h"
#include "esp_sntp.h" //获取网络时间
#include "SD_MMC.h"   //SD卡
#include "stdio.h"
#include "freertos/queue.h"
#include "esp_vfs_fat.h"

#define TAG "MY_APP"
bool ntp_set_success_flag = false;
bool ntp_start_flag = true;

static dht11_data_t dht11_res_data; // 温湿度数据
SemaphoreHandle_t http_Mutex;
QueueHandle_t dht11_Queue; // 声明一个队列

void Sdcard_Task(void *pvParameters)
{

    while (1)
    {
        if (xQueueReceive(dht11_Queue, &dht11_res_data, portMAX_DELAY) == pdPASS) // 接收队列数据
        {
            ESP_LOGI(TAG, "温度:%d 湿度:%d", dht11_res_data.temperature / 10, dht11_res_data.humidity / 10);
        }

        char *name = (char *)malloc(1024);     // 分配内存
        char *data_buf = (char *)malloc(1024); // 分配内存
        
        sprintf(name, "%d-%02d-%02d_%02d.csv", datetime.year, datetime.month, datetime.day, datetime.hour);
        sprintf(data_buf, "%d%02d%02d%02d%02d,%d,%d\n", datetime.year, datetime.month, datetime.day, datetime.hour,datetime.minute,dht11_res_data.temperature / 10, dht11_res_data.humidity / 10);
        ESP_LOGI(TAG, "name:%s", name);

        SD_createFile(name, data_buf); // 写入数据

        free(name);
        free(data_buf);

        vTaskDelay(10000 / portTICK_PERIOD_MS);
    }
}
void my_app_init()
{
    ui_read_val_init(); // ui参数初始化初始化
    ESP_LOGI(TAG, "ui_state_init");
    http_Mutex = xSemaphoreCreateMutex();
    dht11_Queue = xQueueCreate(1, sizeof(dht11_data_t)); // 创建一个队列
    if (SD_Init() == ESP_OK)                             // SD卡初始化
    {
        PCF85063_Read_Time(&datetime); // 读取时间
        ESP_LOGI(TAG, "SD卡初始化成功");
        if (datetime.year < 2022)
        {

            printf("时间未校准，需要设置 %d \r\n", datetime.year);
        }
        else
        {
            xTaskCreatePinnedToCore(Sdcard_Task, "Sdcard_Task", 4096 * 2, NULL, 10, NULL, 1);
            ESP_LOGI(TAG, "创建SD卡任务");
        }
    }
    else
    {
        ESP_LOGI(TAG, "SD卡初始化失败");
    }
}
void time_sync_notification_cb(struct timeval *tv)
{

    time_t now = 0;
    struct tm timeinfo = {0};
    datetime_t my_time = {0};
    time(&now);      // 获取当前时间戳
    now += 8 * 3600; // 转换为北京时间

    localtime_r(&now, &timeinfo); // 获取当前时间
    my_time.year = timeinfo.tm_year + 1900;
    my_time.month = timeinfo.tm_mon + 1;
    my_time.day = timeinfo.tm_mday;
    my_time.hour = timeinfo.tm_hour;
    my_time.minute = timeinfo.tm_min;
    my_time.second = timeinfo.tm_sec;
    ESP_LOGI(TAG, "当前时间：%d-%d-%d %d:%d:%d", my_time.year, my_time.month, my_time.day, my_time.hour, my_time.minute, my_time.second);
    ESP_LOGI(TAG, "timeinfo.tm_year = %d, timeinfo.tm_mon = %d, timeinfo.tm_mday = %d, timeinfo.tm_hour = %d, timeinfo.tm_min = %d, timeinfo.tm_sec = %d", timeinfo.tm_year, timeinfo.tm_mon, timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec);
    PCF85063_Set_All(my_time);
    ntp_set_success_flag = true;
    ntp_start_flag = true;
}
void my_ntp_task(void *pvParameters)
{

    esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org");
    config.sync_cb = time_sync_notification_cb;
    esp_netif_sntp_init(&config); // 初始化sntp/////

    while (1)
    {
        if (ntp_set_success_flag == true)
        {
            esp_netif_sntp_deinit(); // 关闭sntp
            vTaskDelete(NULL);
        }

        if (SetDateTimeFlag == 0 && wifi_connect_flag == 1)
        {

            int retry = 0;
            const int retry_count = 15;

            while (esp_netif_sntp_sync_wait(2000 / portTICK_PERIOD_MS) == ESP_ERR_TIMEOUT && ++retry < retry_count)
            { // 等待sntp同步完成
                ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
                if (ntp_set_success_flag == true)
                {
                    break;
                }
            }
            if (retry == retry_count)
            {
                ESP_LOGI(TAG, "Could not obtain time from sntp");
            }
        }

        ESP_LOGI(TAG, "sntp WAITING ，setdatetimeflag = %d,wifi_connect_flag = %d", SetDateTimeFlag, wifi_connect_flag);

        vTaskDelay(10 / portTICK_PERIOD_MS); // 每10秒检查一次
    }
}
void get_ntp_time(void)
{
    if (ntp_start_flag == true)
    {
        ntp_start_flag = false;

        xTaskCreatePinnedToCore(my_ntp_task, "my_ntp_task", 4096, NULL, 5, NULL, 0);
    }
}